﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Web.Framework;
using WebAppAuthAdmin.AuthApiManagementServiceReference;
using WebAppAuthAdmin.Code;
using AuthApi.Contracts;
using WebAppAuthAdmin.Code.Security;
using System.Text;

namespace WebAppAuthAdmin.App
{
    public partial class UserEdit : BasePage
    {
        private WebApplicationInfo WebApplicationInfo
        {
            get
            {
                return (WebApplicationInfo)this.ViewState["webApp"];
            }
            set
            {
                this.ViewState["webApp"] = value;
            }
        }

        private Company WebCompany
        {
            get
            {
                return (Company)this.ViewState["webCompany"];
            }
            set
            {
                this.ViewState["webCompany"] = value;
            }
        }

        private AdUser AdUser
        {
            get
            {
                return (AdUser)this.ViewState["AdUser"];
            }
            set
            {
                this.ViewState["AdUser"] = value;
            }
        }

        private List<LinkButton> actionButtons = new List<LinkButton>();
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            LinkButton crearContactoButton = new LinkButton();
            crearContactoButton.ID = "guardarButton";
            crearContactoButton.Text = "Guardar";
            crearContactoButton.Click += new EventHandler(lnkGuardar_Click);
            actionButtons.Add(crearContactoButton);

            base.LoadContextActions(actionButtons);
        }

        protected override void ApplySecurity()
        {
            bool hasPermissionForSave;
            bool hasPermissionForPassword;
            if (AdUser.Id == 0)
            {
                hasPermissionForSave = HasPermissionFor(AppSecurity.APP_USER_CREATE_);
                hasPermissionForPassword = HasPermissionFor(AppSecurity.APP_SET_PASSWORD);
            }
            else
            {
                hasPermissionForSave = HasPermissionFor(AppSecurity.APP_USER_EDIT);
                hasPermissionForPassword = HasPermissionFor(AppSecurity.APP_CHANGE_PASSWORD);
            }

            this.lnkGuardar.Visible = hasPermissionForSave;
            actionButtons.Where(a => a.ID == "guardarButton").Single().Visible = hasPermissionForSave;

            this.txtPassword.ReadOnly = !hasPermissionForPassword;
            if (this.txtPassword.ReadOnly)
            {
                this.txtPassword.CssClass += " readonly";
            }

            if (!HasPermissionFor(AppSecurity.APP_USER_BLOCK))
            {
                this.chkUserBloqueado.Enabled = false;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            // Agregar el resetear password en esta pantalla como una acción
            try
            {
                if (!this.IsPostBack)
                {
                    if (this.Request.QueryString["UserName"] != null &&
                        this.Request.QueryString["Application"] != null
                        )
                    {
                        WebApplicationInfo = WebServiceHelper.GetApplicationById(Convert.ToInt32(this.Request.QueryString["Application"]));
                        AdUser = WebServiceHelper.GetUser(WebApplicationInfo.Id, BasePage.CompanyId, this.Request.QueryString["UserName"]);
                        WebCompany = WebServiceHelper.GetCompanyById(BasePage.CompanyId);
                        Bind();

                    }                   
                    else
                    {
                        ExceptionManager.Instance.ShowWarning("La página fue accedida con parametros incorrectos, por favor vuelva a intentar la operación");
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void Bind()
        {
            this.txtAplicacion.Text = WebApplicationInfo.Name;
            this.txtUserName.Text = AdUser.UserName;
            this.txtNombreUsuario.Text = AdUser.GivenName;
            this.lblHasPassword.Text = AdUser.HasPassword ? "SI" : "NO";
            this.chkUserBloqueado.Checked = AdUser.Blocked;
            this.chkIncluido.Checked = AdUser.UsuarioEnAplicacion;

            if (AdUser.Id != 0)
            {
                var rolesForUser = AdUser.Roles;

                this.Grid.DataSource = rolesForUser;
                this.Grid.DataBind();
                //this.chksRoles.DataValueField = "Id";
                //this.chksRoles.DataTextField = "Name";
                //this.chksRoles.DataSource = rolesForUser;
                //this.chksRoles.DataBind();
                //for (int i = 0; i < rolesForUser.Count; i++)
                //{
                //    this.chksRoles.Items[i].Selected = rolesForUser[i].IsIncluded;
                //}                       
            }
        }

        protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    RoleIncluded role = (RoleIncluded)e.Row.DataItem;

                    CheckBox chkSelect = (CheckBox)e.Row.Cells[0].FindControl("chkSelectRow");
                    chkSelect.Checked = role.IsIncluded;
                    if (role.IsIncluded)
                    {
                        this.hidCheckedRows.Value += string.Format("#{0}#", role.Id);
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void Grid_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void SetData()
        {
            AdUser.ApplicationId = WebApplicationInfo.Id;
            AdUser.CompanyId = BasePage.CompanyId;
            AdUser.UserName = this.txtUserName.Text;

            //Obtengo los valores checkeados
            List<int> selectedRowsIds = UIHelper.GetSelectedRowIds(this.hidCheckedRows.Value);

            foreach (var userRole in AdUser.Roles)
            {
                if (selectedRowsIds.Contains(userRole.Id))
                {
                    userRole.IsIncluded = true;
                }
                else
                {
                    userRole.IsIncluded = false;
                }
            }

            this.hidCheckedRows.Value = string.Empty;
        }

        private void Save()
        {
            this.AdUser = WebServiceHelper.SaveUser(this.AdUser);
        }

        protected void lnkGuardar_Click(object sender, EventArgs e)
        {
            try
            {
                SetData();
                Save();
                Bind();
                this.masterPage.ShowMessage("Los permisos se guardaron exitosamente", WebMessageType.Notification);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }
    }
}